Date.prototype.Format = function(fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};


var request = require('request');
var apiUrl = require('../config.json').autoSurveyUrl;
var redisNameSpace = "totalStationServer"; //本程序在redis中的命名空间

function getKeyString(prjName, ptName) {
    return redisNameSpace + ":" + prjName + ":" + ptName.toString();
}

var emmitFactory = (function() {
    var emmitFactory = function(server, redisClient) {
        var redis = require('redis');

        this.Server = server || null;

        this.SurveyComplete = function(jsonData) {
            var _this = this;
            var prjName = jsonData.Target;
            request({
                url: apiUrl + '/stations',
                qs: {
                    'prjName': prjName
                }
            }, function(error, response, body) {
                if (!error && response.statusCode === 200) {
                    jsonData.Url = JSON.parse(body);
                    request({
                        url: apiUrl + '/lastresults',
                        qs: {
                            'prjName': prjName
                        }
                    }, function(err, res, body) {
                        if (!error && response.statusCode === 200) {
                            var data = JSON.parse(body);
                            if (typeof(data) === 'string') {
                                data = JSON.parse(data);
                            }
                            jsonData.LastResult = data;
                            _this.SendCommand('SurveyComplete', jsonData);
                        }
                    });
                }
            });
        };
        this.StartSurvey = function(jsonData) {
            this.SendCommand('StartSurvey', jsonData);
        };
        this.StopSurvey = function(jsonData) {
            this.SendCommand('StopSurvey', jsonData);
        }
        this.PlainText = function(jsonData) {
            this.SendCommand('PlainText', jsonData);
        };
        this.OffLine = function(jsonData) {
            this.SendCommand('PlainText', jsonData);
        };
        this.GetAllPoints = function(jsonData) {
            this.SendCommand('GetAllPoints', jsonData);
        };
        this.MeasurePoint = function(jsonData, ptName) {
            jsonData.PointName = ptName;
            console.log('send MeasurePoint cmd to Browser!!');
            this.SendCommand('MeasurePoint', jsonData);
        };

        function generateJsonData(jsonData, ptName, ptValue) {
            var list = jsonData.Data.list;
            jsonData.Valid = false;
            if (list.length > 0) {
                var lastValue = parseFloat(list[list.length - 1].value);
                var diff = (ptValue - lastValue) * 1000;
                diff = parseFloat(diff.toFixed(1));
                jsonData.Diff = diff;
            } else {
                jsonData.Diff = -100;
            }
            var deformation = Math.abs(jsonData.Diff); //取绝对值

            if (deformation < 10 && ptValue > 5.005) {
                jsonData.Valid = true;
                var newItem = {
                    value: ptValue,
                    time: new Date().Format("MM-dd hh:mm")
                };
                if (list[list.length - 1].time !== newItem.time) {
                    jsonData.Data.list.push(newItem);
                }
                if (ptValue + 0.003 > jsonData.Data.max) {
                    jsonData.Data.max = ptValue + 0.003;
                } else if (ptValue - 0.003 < jsonData.Data.min) {
                    jsonData.Data.min = ptValue - 0.003;
                }
                if (list.length > 11) {
                    list.splice(0, 1);
                }
            }
            jsonData.PointValue = ptValue;
            jsonData.PointName = ptName;
            console.log('store %s', getKeyString(jsonData.Target, ptName));
            return jsonData;
        }

        this.MeasureValue = function(jsonData, ptName, ptValue) {
            var _this = this;
            var prjName = jsonData.Target;
            redisClient.get(getKeyString(prjName, ptName), (function(prjName, jsonData) {
                return function(err, reply) {
                    if (!reply) {
                        request({
                            url: apiUrl + '/recentvalues',
                            qs: {
                                'prjName': prjName,
                                'ptName': ptName
                            }
                        }, (function(jsonData, ptName, ptValue) {
                            ptValue = parseFloat(ptValue);
                            return function(error, response, body) {
                                if (!error && response.statusCode === 200) {
                                    //body = {name:string,list:[{value:string,time:string}],min:number,max:number,interval:number}
                                    var data = JSON.parse(body);
                                    if (typeof(data) === 'string') {
                                        data = JSON.parse(data);
                                    }
                                    jsonData.Data = data;
                                    jsonData.HasRecent = true;
                                    jsonData = generateJsonData(jsonData, ptName, ptValue);
                                    _this.SendCommand('MeasureValue', jsonData);
                                }
                            };
                        })(jsonData, ptName, ptValue));
                    } else {
                        console.log("got data in redis: %s", getKeyString(prjName, ptName));
                        jsonData = JSON.parse(reply);
                        jsonData = generateJsonData(jsonData, ptName, ptValue);
                        _this.SendCommand('MeasureValue', jsonData);
                    }
                }
            })(prjName, jsonData));
        };


    };
    emmitFactory.prototype.SendCommand = function(type, data) {
        var targetTps = data.Target;
        //遍历所有的用户,一旦用户有选择这个设备,就把数据发送过去
        for (var i = 0; i < this.Server.WebClientList.length; i++) {
            for (var j = 0; j < this.Server.WebClientList[i].Name.length; j++) {
                if (this.Server.WebClientList[i].Name[j] === targetTps) {
                    this.Server.WebClientList[i].EmitData(type, data);
                }
            }
        }
    };
    return emmitFactory;
})();


module.exports = emmitFactory;
